/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 4; tab-width: 4 -*-  */
/*
 * catchit
 * Copyright (C) 2013 Ryan Grinkewitz <graphite@Toto>
 * 
 */

#include "sprite-manager.h"

//SpriteManager* SpriteManager::spriteManagerInstance = NULL; 
	 
//SpriteManager* SpriteManager::getInstance()
//{
//	if (!spriteManagerInstance){ 
//		spriteManagerInstance = new SpriteManager;
//	}
	 
//	return spriteManagerInstance;
//}

int SpriteManager::loadSpriteSheet(std::string sprite_sheet, int sprite_size, 
	                    int sheet_size){
	int retval = 0;
	SDL_Surface* raw_image;

	raw_image = IMG_Load (sprite_sheet.c_str());


	if(raw_image != NULL){

		sprite_sheet_image = SDL_DisplayFormat (raw_image);
		SDL_FreeSurface (raw_image);

		
	}else{
		retval = -1;
	}

	if(sprite_sheet_image != NULL){
		SDL_SetColorKey( sprite_sheet_image, SDL_SRCCOLORKEY, 
		                SDL_MapRGB( sprite_sheet_image->format, 0xFF, 0xFF, 0xFF ) );
	}else{
		retval = -2;
	}
	
	this->sprite_size = sprite_size;
	this->sprite_count = pow(sheet_size, 2);

	sprites = new SDL_Rect[sprite_count];

	int sprite_index = 0;
	
	for(int i = 0; i < sheet_size; i++){
		for(int j = 0; j < sheet_size; j++){
			sprites[sprite_index].w = sprite_size;
			sprites[sprite_index].h = sprite_size;		
			sprites[sprite_index].y = i * sprite_size;
			sprites[sprite_index].x = j * sprite_size;
			sprite_index++;
			if(sprite_index > sprite_count){
				exit(-1);
			}
			
		}
	}



	return 0;
}

int loadSpriteSheet(std::string sprite_sheet, std::string sprite_map){
	//determine configuration file format, etc
	
	return 0;
}



int SpriteManager::displaySprite(int sprite_index, int x, int y, SDL_Surface* display_surface){
	int retval = 0;
	
	SDL_Rect position;
	
	position.x = x;
	position.y = y;

	SDL_BlitSurface(sprite_sheet_image, &sprites[sprite_index], display_surface,
	                &position);

	
	return retval;
}


void SpriteManager::displaySpriteSheetTest(SDL_Surface* screen, int width, 
                                           int height)
{
	loadSpriteSheet("sprite_test.png", 64, 8);

	SDL_FillRect( screen, &screen->clip_rect, 
	             SDL_MapRGB( screen->format, 0xFF, 0xFF, 0xFF ) );	

	for(int i = 0; i < sprite_count; i++){
		displaySprite(i, width/2 - sprite_size/2, 
		              height/2 - sprite_size/2, screen);
		SDL_Flip(screen);

		SDL_Delay (1000);

		SDL_FillRect( screen, &screen->clip_rect, 
	             SDL_MapRGB( screen->format, 0xFF, 0xFF, 0xFF ) );	
		SDL_Flip (screen);

		SDL_Delay (1000);
		
	}

	
}
